<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input class="filter-input-container" v-model="listQuery.keyWord" clearable style="width: 200px;"
        placeholder="请输入店长名称" />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button class="filter-item" icon="el-icon-refresh-right" @click="handleReset">重置</el-button>

      <el-button class="filter-item add" type="primary" icon="el-icon-circle-plus-outline"
        @click="handleAdd">添加店长</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table stripe v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit
      highlight-current-row>
      <el-table-column align="center" width="100px" label="用户ID" prop="userId" sortable />
      <el-table-column align="center" label="用户名" prop="userName" />
      <el-table-column align="center" label="性别" prop="genderStr">
        <template slot-scope="scope">
          {{ scope.row.genderStr || "-" }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="真实姓名" prop="fullName" />
      <el-table-column align="center" label="用户头像" width="80">
        <template slot-scope="scope">
          <el-avatar :src="scope.row.imgUrl" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="手机号码" prop="phone" />
      <el-table-column align="center" label="生日" prop="birthday" />
      <el-table-column align="center" label="用户类型" prop="userTypeStr">
      </el-table-column>
      <el-table-column align="center" label="最近登录时间" prop="lastLoginTime">
        <template slot-scope="scope">
          {{ scope.row.lastLoginTime || "-" }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="用户状态" prop="status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status | statusFilter">{{
            getLabel(userStatus, scope.row.status)
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="250" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="info" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button v-if="scope.row.status === '1'" type="danger" size="mini"
            @click="handleModifyUserStatus(scope.row, 'stop')">停用</el-button>
          <el-button v-if="scope.row.status === '0'" type="success" size="mini"
            @click="handleModifyUserStatus(scope.row, 'open')">启用</el-button>
          <el-button type="primary" size="mini" @click="handleDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize"
      @pagination="getList" />
    <!-- 用户详情对话框 -->
    <el-dialog @close="handleClose" width="45%" :visible.sync="userDialogVisible" title="店长信息">
      <el-form :rules="rules" size="large" ref="userDetail" :model="userDetail" status-icon label-position="left"
        label-width="100px" style="width: 80%; margin-left:20px;">
        <el-form-item label="用户名" prop="userName">
          <el-input placeholder="请输入用户名（登陆账号）" clearable v-model="userDetail.userName"
            :disabled="dialogType === 'edit'" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="fullName">
          <el-input placeholder="请输入真实姓名" clearable v-model="userDetail.fullName" />
        </el-form-item>
        <el-form-item label="用户手机" prop="phone">
          <el-input @blur="handleBlur" placeholder="请输入手机号码" clearable v-model="userDetail.phone" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item inline-block label="生日" prop="birthday">
              <el-date-picker clearable v-model="userDetail.birthday" type="date" placeholder="请选择日期">
              </el-date-picker>
            </el-form-item></el-col>
          <el-col :span="12"><el-form-item label="用户性别" prop="genderStr">
              <el-select clearable v-model="userDetail.gender" placeholder="请选择"><el-option v-for="item in sexTypeDict"
                  :key="item.value" :label="item.label" :value="item.value" /></el-select>
            </el-form-item></el-col>
        </el-row>
        <el-form-item v-if="dialogType == 'add'" label="默认密码" prop="password">
          <el-input placeholder="请输入密码" clearable v-model="userDetail.password" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="userDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUserUpdate('userDetail')">确定</el-button>
      </div>
    </el-dialog>
    <el-drawer size="30%" title="用户信息" @close="handleCloseDrawer" :visible.sync="userDrawerVisible" :with-header="false">
      <div class="user-detail-box">
        <el-descriptions title="用户信息" size="medium" :column="2" border>
          <el-descriptions-item label="用户名/登陆账号">{{ userDetail.userName }}</el-descriptions-item>
          <el-descriptions-item label="真实姓名">{{ userDetail.fullName }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ userDetail.phone }}</el-descriptions-item>
          <el-descriptions-item label="生日">{{ userDetail.birthday }}</el-descriptions-item>
          <el-descriptions-item label="用户类型">
            <el-tag size="small">{{ userDetail.userTypeStr }}</el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-drawer>


    <!-- 账号密码信息 -->
    <el-dialog @close="handleClose" width="25%" :visible.sync="userAccountVisiable" title="账号密码信息">
      <el-result icon="success" title="添加成功！" :subTitle="userAccount">
        <template slot="extra">
          <el-button type="primary" size="medium" @click="copyText(userAccount)">一键复制账号密码</el-button>
        </template>
      </el-result>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, userDetail, updateUserStatus, userAdd, judgeSingle, updateUser } from '@/api/user'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { getLabel } from "@/utils/index.js"
import { userStatus, sexTypeDict } from "@/data/dict.js"
import { validateMobilePhone } from "@/utils/check.js";
import { Base64 } from 'js-base64';
import clipboard from 'clipboard';

export default {
  name: 'User',
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: "danger",
        1: "success",
        2: "info",
      };
      return statusMap[status];
    },
  },
  data() {
    return {
      userAccount: "",
      rules: {
        userName: [
          { required: true, message: '请输入用户名/登录账号', trigger: 'blur' }
        ],
        fullName: [
          { required: true, message: '请输入真实姓名', trigger: 'blur' }
        ],
        birthday: [
          { required: true, message: '请选择日期', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号码' },
          { validator: this.validateMobilePhone },
        ],
        password: [
          { required: true, message: '请输入默认密码' },
        ],
      },
      userStatus,
      sexTypeDict,
      list: [],
      total: 0,
      listLoading: true,
      userAccountVisiable: false,
      listQuery: {
        userType: "1",
        currentPage: 1,
        pageSize: 20,
        keyWord: ''
      },
      downloadLoading: false,
      genderDic: ['男', '女'],
      levelDic: ['普通用户', 'VIP用户', '高级VIP用户'],
      statusDic: ['可用', '禁用', '注销'],
      userDialogVisible: false,
      userDrawerVisible: false,
      userDetail: {
        userName: "",
        phone: "",
        fullName: "",
        password: "123456",
        birthday: ""
      },
      dialogType: 'edit' //弹窗类型
    }
  },
  created() {
    this.getList()
  },
  methods: {
    validateMobilePhone,
    copyText(val) {
      var cInput = document.createElement("input");
      cInput.value = val;
      document.body.appendChild(cInput);
      cInput.select();
      document.execCommand("copy");
      this.$message.success("复制成功")
      document.body.removeChild(cInput);
    },
    checkPhone(value) {
      // 手机号验证
      if (!value) {
        this.$message.info("手机号不能为空");
        return
      } else {
        const reg = /^1[3456789]\d{9}$/;
        if (reg.test(value)) {
        } else {
          this.$message.info("请输入正确的手机号");
          return
        }
      }
    },
    getLabel,
    getList() {
      this.listLoading = true
      if (this.listQuery.userId) {
        userDetail(this.listQuery.userId).then(response => {
          this.list = []
          if (response.data) {
            this.list.push(response.data)
            this.total = 1
            this.listLoading = false
          } else {
            this.list = []
            this.total = 0
            this.listLoading = false
          }
        }).catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
      } else {
        fetchList(this.listQuery).then(response => {
          console.log('response', response)
          this.list = response.data.records
          this.total = response.data.total
          this.listLoading = false
        }).catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
      }
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleDetail(row) {
      this.userDetail = row
      this.userDrawerVisible = true
    },
    //用户状态修改
    handleModifyUserStatus(row, type) {
      let text = type === 'stop' ? "确认停用该用户信息？" : "确认启用该用户信息？";
      this.$confirm(text, '状态变更提醒', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // console.log('row---------------', row);
        let params = {
          userId: row.userId,
          status: type === "stop" ? "0" : "1"
        }
        updateUserStatus(params).then((res) => {
          if (res.code === 200) {
            this.$message.success("状态更新成功！")
            this.getList();
          } else {
            this.$message.error("数据更新失败，请联系管理员")
          }
        })
      }).catch(() => {
        console.log('cancel');
      })
    },
    handleUserUpdate(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.dialogType === 'edit') {
            updateUser(this.userDetail)
              .then((response) => {
                this.userDialogVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '更新用户成功'
                })
                this.getList();
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: response.data.errmsg
                })
              })
          } else {
            let params = { ...this.userDetail }
            params.userType = '1'
            params.password = Base64.encode(params.password)
            userAdd(params).then(res => {
              if (res.code === 200) {
                console.log('res=================', res);
                this.userDetail = {}
                this.userDialogVisible = false;
                this.userAccountVisiable = true;
                this.userAccount = "账号:" + res.data.userName + "/密码:" + res.data.password;
                // this.$message.success("添加成功！")
                this.getList();
              }
            })
          }
        } else {
          return false;
        }
      });


    },
    //重置
    handleReset() {
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        keyWord: ''
      }
      this.getList();
    },
    //编辑弹窗
    handleEdit(row) {
      this.userDialogVisible = true
      this.userDetail = JSON.parse(JSON.stringify(row))
    },
    //添加用户
    handleAdd() {
      this.dialogType = 'add'
      this.userDetail.password = "123456"
      this.userDialogVisible = true;
    },
    handleClose() {
      this.userDialogVisible = false;
      this.userDetail = {}
      this.dialogType = 'edit'
    },
    handleCloseDrawer() {
      this.userDrawerVisible = false;
      this.userDetail = {}
      this.dialogType = 'edit'
    },
    //账号实时校验
    handleBlur() {
      let params = {
        userName: this.userDetail.userName,
        phone: this.userDetail.phone
      }
      judgeSingle(params).then((res) => {
        if (res.code === 200) {
          console.log('res==============', res);
          let phoneValid = res.data.phoneFlag;
          let userNameValid = res.data.userNameFlag;
          if (phoneValid === "true") {
            this.$message.info("该手机号码已注册，请检查后重试！")
            this.userDetail.phone = "";
            return;
          } else if (userNameValid === "true") {
            this.$message.info("该用户名已注册，请检查后重试！")
            return;
          }
        }
      })
    }

  }
}
</script>
<style lang="scss" scoped>
.filter-item {
  margin-left: 20px;
  vertical-align: initial;

  &.add {
    float: right;
  }
}

.filter-input-container {
  margin-left: 0px
}

.user-detail-box {
  padding: 16px;
}

:deep(.el-drawer__header) {
  height: 20px;
  margin-bottom: 10px;
}
</style>
